package test2;


import cn.hutool.json.JSONObject;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @author liule
 * @date 2023/8/7 14:37
 * @Desc : 发送application/json类型的post请求
 */
public class HttpClientTest4_post_json {
    public static void main(String[] args) throws Exception {
        //可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlstr = "http://localhost:8899/httpclient-demo/testJson";
        // 创建HttpPost
        HttpPost httpPost = new HttpPost(urlstr);

        //string:是个json字符串
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("userName", "java乐之者");
        jsonObj.put("password", "不知道些什么");
        StringEntity jsonEntity = new StringEntity(jsonObj.toString(), Consts.UTF_8);
        //也需要给entity设置一下内容类型
        jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json; charset=utf-8"));
        jsonEntity.setContentEncoding(Consts.UTF_8.name());

        httpPost.setEntity(jsonEntity);

        // 可关闭的响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpPost);
            // 代表本次请求的成功失败的状态
            StatusLine statusLine = response.getStatusLine();
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                HttpEntity entity = response.getEntity();
                String toStringSesult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringSesult);
                EntityUtils.consume(entity); // 确保流关闭
            } else {
                System.out.println("响应失败，响应码：" + statusLine.getStatusCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }

    }
}
